package strategy

import (
	"fmt"
	"strconv"
	"strings"
	"super/constant"
	"super/global"

	"github.com/nguyenthenguyen/docx"
)

type InsertDocStrategy struct {
}

func (insertDocs InsertDocStrategy) Init() {
	global.CurStatus = constant.InsertDoc
	fmt.Print("insertDoc>")
}

func (InsertDocStrategy) Handle(str string) {
	createInsertDoc(str)
	fmt.Print("insertDoc>")
}
func createInsertDoc(sql string) {
	replaceDocx, err := docx.ReadDocxFile("./insert.docx")
	if err != nil {
		fmt.Println(err)
		return
	}
	docx := replaceDocx.Editable()
	// docx.Replace("${db}", "lawsuit", 1)
	// docx.Replace("${table}", "tu_dm_kz", 1)

	indexA := strings.Index(sql, "(")
	indexB := strings.Index(sql, ")")
	lastIndexA := strings.LastIndex(sql, "(")
	lastIndexB := strings.LastIndex(sql, ")")
	fields := strings.Split(sql[indexA+1:indexB], ",")
	vals := strings.Split(sql[lastIndexA+1:lastIndexB], ",")
	j := 0
	for i, v := range fields {
		if strings.ToLower(vals[i]) == "null" {
			continue
		}
		docx.Replace("${h"+strconv.Itoa(j)+"}", v, 1)
		val := strings.ReplaceAll(vals[i], "'", "")
		docx.Replace("${v"+strconv.Itoa(j)+"}", val, 1)
		j++
	}

	err = docx.WriteToFile("./insertFinish.docx")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("create successful!")
	}
	replaceDocx.Close()
}
